package com.app.util.file.struct;

import java.util.List;
import java.util.Map.Entry;

import com.app.util.param.Param;
import com.app.util.param.ParamMap;
import com.app.util.param.ParamUtil;

/**
 * 头信息，格式：<br />
 * name1=value1<br />
 * name2=value2<br />
 * name3=value3<br />
 * nameN=valueN<br />
 * 
 * @author yao
 */
public class Params extends ParamMap {

	private static final long serialVersionUID = -838977167088770100L;

	private final static ParamUtil keyValueUtil = new ParamUtil("=", "\\n");

	/** 换行符 */ 
	private static final String lineSeparator = (String) java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));

	public static Params fromParamString(String headString) {
		Params params = new Params();
		ParamMap kvMap = keyValueUtil.parseParamList(headString);
		for (List<Param> list : kvMap.values()) {
			for (Param nv : list) {
				params.add(new Param(nv.getName(), nv.getValue()));
			}
		}
		return params;
	}

	public static Param parseParam(String lineString) {
		Param kv = keyValueUtil.parseParam(lineString);
		return new Param(kv.getName(), kv.getValue());
	}

	public String toString() {
		final StringBuffer sb = new StringBuffer();
		for (Entry<String, List<Param>> ent : entrySet()) {
			for (Param h : ent.getValue()) {
				if (sb.length() > 0) {
					sb.append(lineSeparator);
				}
				sb.append(h.getName()).append("=").append(h.getValue());
			}
		}
		System.out.println(sb);
		return sb.toString();
	}

}
